<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书馆管理系统 - 财务管理</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="auth.js"></script>
    <script src="permission-control.js"></script>
    <style>
        /* 财务管理页面特有样式 */
        .tab-container {
            margin-bottom: 20px;
            display: flex;
            border-bottom: 1px solid #ddd;
        }

        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border: none;
            background: none;
            font-size: 1rem;
            color: #777;
            position: relative;
            transition: color 0.2s;
        }

        .tab.active {
            color: #667eea;
            font-weight: 500;
        }

        .tab.active::after {
            content: '';
            position: absolute;
            bottom: -1px;
            left: 0;
            width: 100%;
            height: 3px;
            background-color: #667eea;
        }

        .tab-content {
            display: none;
            padding: 20px;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .tab-content.active {
            display: block;
        }

        .fee-calculator {
            margin-top: 20px;
            padding: 20px;
            background-color: #f8f9fa;
            border-radius: 10px;
            border: 1px solid #e1e5e9;
        }

        .fee-calculator h4 {
            margin-bottom: 15px;
            color: #333;
            padding-bottom: 10px;
            border-bottom: 1px solid #e1e5e9;
        }

        .fee-item {
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 15px;
            flex-wrap: wrap;
            padding: 10px 0;
            border-bottom: 1px dashed #e1e5e9;
        }

        .fee-item:last-child {
            border-bottom: none;
        }

        .fee-item label {
            min-width: 140px;
            color: #555;
            font-weight: 500;
        }

        .fee-result {
            padding: 6px 12px;
            border-radius: 4px;
            flex-grow: 1;
            font-size: 0.95rem;
        }

        .fee-result.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .fee-result.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .fee-result.info {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }

        .ratio-input {
            width: 100px;
        }

        .stats {
            margin-bottom: 25px;
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
        }

        .payment-detail {
            padding: 10px;
        }

        .detail-row {
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px dashed #e1e5e9;
        }

        .detail-row:last-child {
            border-bottom: none;
        }

        .detail-row label {
            display: inline-block;
            width: 120px;
            font-weight: 500;
            color: #555;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .fee-item {
                flex-direction: column;
                align-items: flex-start;
            }

            .fee-item label {
                min-width: auto;
                margin-bottom: 5px;
            }

            .stats {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
<!-- 主系统页面结构 -->
<div id="mainPage" class="page active">
    <!-- 顶部导航栏 -->
    <header class="header">
        <div class="header-left">
            <button class="sidebar-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="logo">
                <i class="fas fa-book"></i>
                图书馆管理系统
            </h1>
        </div>
        <div class="header-right">
            <div class="notification-icon" onclick="showNotifications()">
                <i class="fas fa-bell"></i>
                <span class="notification-badge" id="notificationBadge">0</span>
            </div>
            <div class="user-menu">
                <span class="user-name" id="currentUserName">管理员</span>
                <div class="user-dropdown">
                    <button class="dropdown-btn">
                        <i class="fas fa-user-circle"></i>
                        <i class="fas fa-chevron-down"></i>
                    </button>
                    <div class="dropdown-content">
                        <a href="#" onclick="showProfile()">个人资料</a>
                        <a href="#" onclick="changePassword()">修改密码</a>
                        <a href="#" onclick="logout()">退出登录</a>
                    </div>
                </div>
            </div>
        </div>
    </header>

    <!-- 侧边栏 -->
    <aside class="sidebar" id="sidebar">
        <nav class="sidebar-nav">
            <ul id="sidebarMenu">
                <!-- 菜单将通过JavaScript动态生成 -->
            </ul>
        </nav>
    </aside>

    <!-- 主内容区域 -->
    <main class="main-content">
        <!-- 财务管理页面 -->
        <div id="payments" class="content-page active">
            <div class="page-header">
                <h2>财务管理</h2>
            </div>

            <!-- 标签页容器 -->
            <div class="tab-container">
                <div class="tab active" onclick="switchTab('feeManagement')">费用管理</div>
                <div class="tab" onclick="switchTab('paymentRecords')">付费记录与统计</div>
            </div>

            <!-- 费用管理标签内容 -->
            <div id="feeManagement" class="tab-content active">
                <h3>费用管理</h3>
                <div class="fee-calculator">
                    <h4>费用计算</h4>

                    <!-- 逾期罚款计算 -->
                    <div class="fee-item">
                        <label for="overdueUserId">用户ID:</label>
                        <input type="text" id="overdueUserId" class="form-control" placeholder="输入用户ID">
                        <button class="btn btn-sm btn-primary" onclick="calculateOverdueFee()">计算并添加逾期罚款</button>
                        <span id="overdueFeeResult" class="fee-result"></span>
                    </div>

                    <!-- 图书损坏赔偿计算 -->
                    <div class="fee-item">
                        <label>图书损坏赔偿计算:</label>
                        <input type="text" id="damageUserId" class="form-control" placeholder="输入用户ID">
                        <input type="text" id="damagedBookId" class="form-control" placeholder="输入损坏图书ID">
                        <label>赔偿比例:</label>
                        <input type="number" step="0.01" min="0.01" max="2" value="0.5"
                               class="form-control ratio-input" id="damageRatio" placeholder="例如0.5">
                        <span>（按图书价格的比例计算）</span>
                        <button class="btn btn-sm btn-primary" onclick="calculateDamageFee()">计算并添加赔偿费用</button>
                        <span id="damageFeeResult" class="fee-result"></span>
                    </div>

                    <!-- 图书丢失赔偿计算 -->
                    <div class="fee-item">
                        <label>图书丢失赔偿计算:</label>
                        <input type="text" id="lostUserId" class="form-control" placeholder="输入用户ID">
                        <input type="text" id="lostBookId" class="form-control" placeholder="输入丢失图书ID">
                        <label>赔偿比例:</label>
                        <input type="number" step="0.01" min="0.01" max="3" value="1.2"
                               class="form-control ratio-input" id="lostRatio" placeholder="例如1.2">
                        <span>（按图书价格的比例计算）</span>
                        <button class="btn btn-sm btn-primary" onclick="calculateLostFee()">计算并添加赔偿费用</button>
                        <span id="lostFeeResult" class="fee-result"></span>
                    </div>
                </div>
            </div>

            <!-- 付费记录与统计标签内容 -->
            <div id="paymentRecords" class="tab-content">
                <div class="page-filters">
                    <div class="filter-group">
                        <input type="text" id="paymentSearch" placeholder="搜索支付记录（用户ID或用户名）..." class="form-control">
                        <select id="paymentStatusFilter" class="form-control">
                            <option value="">所有状态</option>
                            <option value="unpaid">待支付</option>
                            <option value="paid">已支付</option>
                            <option value="refunded">已取消</option>
                        </select>
                        <select id="paymentTypeFilter" class="form-control">
                            <option value="">所有类型</option>
                            <option value="overdue_fee">逾期罚款</option>
                            <option value="damage_fee">损坏赔偿</option>
                            <option value="loss_fee">丢失赔偿</option>
                        </select>
                        <button class="btn btn-secondary" onclick="searchPayments()">
                            <i class="fas fa-search"></i>
                            搜索
                        </button>
                    </div>
                </div>
                <div class="stats">
                    <div class="stat-card">
                        <div class="stat-label">待缴金额总计</div>
                        <div class="stat-value" id="pendingAmount">¥0.00</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">已缴金额总计</div>
                        <div class="stat-value" id="paidAmount">¥0.00</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">逾期罚款数</div>
                        <div class="stat-value" id="overdueCount">0</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">损坏赔偿数</div>
                        <div class="stat-value" id="damageCount">0</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">丢失赔偿数</div>
                        <div class="stat-value" id="lostCount">0</div>
                    </div>
                </div>
                <div class="table-container">
                    <table class="data-table">
                        <thead>
                        <tr>
                            <th>ID</th>
                            <th>用户</th>
                            <th>费用类型</th>
                            <th>金额</th>
                            <th>支付方式</th>
                            <th>状态</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody id="paymentTableBody">
                        </tbody>
                    </table>
                </div>
                <div class="pagination" id="paymentPagination">
                </div>
                <div class="pagination-tools" id="paymentPaginationTools"></div>
            </div>
        </div>
    </main>
</div>

<!-- 模态框 -->
<div id="modalOverlay" class="modal-overlay">
    <div class="modal">
        <div class="modal-header">
            <h3 id="modalTitle">标题</h3>
            <button class="modal-close" onclick="closeModal()">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="modal-body" id="modalBody">
        </div>
        <div class="modal-footer" id="modalFooter">
        </div>
    </div>
</div>

<!-- 加载提示 -->
<div id="loadingOverlay" class="loading-overlay">
    <div class="loading-spinner">
        <i class="fas fa-spinner fa-spin"></i>
        <p>加载中...</p>
    </div>
</div>

<!-- 消息提示 -->
<div id="messageContainer" class="message-container">
</div>

<script>
    // API基础配置
    const API_BASE_URL = 'http://118.31.223.190:8080';

    // 定义费用类型枚举映射 - 对应数据库中的枚举值
    const FEE_TYPE_ENUM = {
        'overdue_fee': '逾期罚款',
        'damage_fee': '损坏赔偿',
        'loss_fee': '丢失赔偿'
    };

    // 通用API请求函数
    class ApiClient {
        constructor() {
            this.baseURL = API_BASE_URL;
        }

        async request(url, options = {}) {
            const isForm = options && options.body instanceof FormData;
            const headers = isForm ? (options.headers || {}) : { 'Content-Type': 'application/json', ...(options.headers || {}) };
            const config = { headers, ...options };

            try {
                const response = await fetch(`${this.baseURL}${url}`, config);
                const data = await response.json();

                if (!response.ok) {
                    throw new Error(data.message || `HTTP error! status: ${response.status}`);
                }

                return data;
            } catch (error) {
                console.error('API请求失败:', error);
                throw error;
            }
        }

        async get(url, params = {}) {
            const queryString = new URLSearchParams(params).toString();
            const fullUrl = queryString ? `${url}?${queryString}` : url;
            return this.request(fullUrl, { method: 'GET' });
        }

        async post(url, data = {}) {
            if (data instanceof FormData) {
                return this.request(url, { method: 'POST', body: data });
            }
            return this.request(url, { method: 'POST', body: JSON.stringify(data) });
        }

        async put(url, data = {}) {
            return this.request(url, {
                method: 'PUT',
                body: JSON.stringify(data)
            });
        }

        async delete(url) {
            return this.request(url, { method: 'DELETE' });
        }
    }

    // 创建API客户端实例
    const api = new ApiClient();

    // 支付管理API
    const PaymentAPI = {
        // 完成支付
        completePayment: (paymentId, payMethod) =>
            api.post(`/api/payments/${paymentId}/complete?payMethod=${payMethod}`),

        // 取消支付
        cancelPayment: (paymentId) => api.post(`/api/payments/${paymentId}/cancel`),

        // 获取支付详情
        getPaymentById: (paymentId) => api.get(`/api/payments/${paymentId}`),

        // 分页查询支付记录
        pagePayments: (page = 1, size = 10, keyword = '', feeType = '', status = '') =>
            api.get('/api/payments/page', { page, size, keyword, feeType, status }),

        // 计算并添加逾期罚款
        calculateOverdueFee: (userId) => api.get(`/api/fees/overdue`, { userId }),

        // 计算并添加损坏赔偿
        calculateDamageFee: (userId, bookId, damageRatio) =>
            api.get(`/api/fees/damage`, { userId, bookId, damageRatio }),

        // 计算并添加丢失赔偿
        calculateLostFee: (userId, bookId, lostRatio) =>
            api.get(`/api/fees/lost`, { userId, bookId, lostRatio }),

        // 获取统计数据
        getStatistics: () => api.get(`/api/payments/statistics`)
    };

    // 工具函数
    const Utils = {
        // 显示加载状态
        showLoading: () => {
            const loadingOverlay = document.getElementById('loadingOverlay');
            if (loadingOverlay) {
                loadingOverlay.classList.add('active');
            }
        },

        // 隐藏加载状态
        hideLoading: () => {
            const loadingOverlay = document.getElementById('loadingOverlay');
            if (loadingOverlay) {
                loadingOverlay.classList.remove('active');
            }
        },

        // 显示消息提示
        showMessage: (message, type = 'info', duration = 3000) => {
            const messageContainer = document.getElementById('messageContainer');
            if (!messageContainer) return;

            const messageEl = document.createElement('div');
            messageEl.className = `message ${type}`;

            const iconMap = {
                success: 'fas fa-check-circle',
                error: 'fas fa-exclamation-circle',
                warning: 'fas fa-exclamation-triangle',
                info: 'fas fa-info-circle'
            };

            messageEl.innerHTML = `
                    <i class="${iconMap[type] || iconMap.info}"></i>
                    <span>${message}</span>
                    <button class="message-close" onclick="this.parentElement.remove()">
                        <i class="fas fa-times"></i>
                    </button>
                `;

            messageContainer.appendChild(messageEl);

            // 自动移除消息
            setTimeout(() => {
                if (messageEl.parentElement) {
                    messageEl.remove();
                }
            }, duration);
        },

        // 格式化日期
        formatDate: (dateString) => {
            if (!dateString) return '-';
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        },

        // 格式化金额
        formatMoney: (amount) => {
            if (amount === null || amount === undefined) return '¥0.00';
            return `¥${parseFloat(amount).toFixed(2)}`;
        },

        // 创建分页组件
        createPagination: (currentPage, totalPages, onPageChange) => {
            const pagination = document.createElement('div');
            pagination.className = 'pagination';

            // 上一页按钮
            const prevBtn = document.createElement('button');
            prevBtn.textContent = '上一页';
            prevBtn.disabled = currentPage <= 1;
            prevBtn.onclick = () => onPageChange(currentPage - 1);
            pagination.appendChild(prevBtn);

            // 页码按钮
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);

            if (startPage > 1) {
                const firstBtn = document.createElement('button');
                firstBtn.textContent = '1';
                firstBtn.onclick = () => onPageChange(1);
                pagination.appendChild(firstBtn);

                if (startPage > 2) {
                    const ellipsis = document.createElement('span');
                    ellipsis.textContent = '...';
                    ellipsis.style.padding = '0.5rem';
                    pagination.appendChild(ellipsis);
                }
            }

            for (let i = startPage; i <= endPage; i++) {
                const pageBtn = document.createElement('button');
                pageBtn.textContent = i;
                pageBtn.className = i === currentPage ? 'active' : '';
                pageBtn.onclick = () => onPageChange(i);
                pagination.appendChild(pageBtn);
            }

            if (endPage < totalPages) {
                if (endPage < totalPages - 1) {
                    const ellipsis = document.createElement('span');
                    ellipsis.textContent = '...';
                    ellipsis.style.padding = '0.5rem';
                    pagination.appendChild(ellipsis);
                }

                const lastBtn = document.createElement('button');
                lastBtn.textContent = totalPages;
                lastBtn.onclick = () => onPageChange(totalPages);
                pagination.appendChild(lastBtn);
            }

            // 下一页按钮
            const nextBtn = document.createElement('button');
            nextBtn.textContent = '下一页';
            nextBtn.disabled = currentPage >= totalPages;
            nextBtn.onclick = () => onPageChange(currentPage + 1);
            pagination.appendChild(nextBtn);

            return pagination;
        }
    };

    // 全局变量
    let currentUser = null;
    let currentPageNum = 1;
    let currentPageSize = 10;

    // 页面初始化
    document.addEventListener('DOMContentLoaded', function() {
        initializeApp();
    });

    // 初始化应用
    function initializeApp() {
        // 使用通用权限检查
        if (!initializePagePermission()) {
            return;
        }
        
        currentUser = authManager.getCurrentUser();

        // 生成动态菜单
        generateSidebarMenu();

        // 更新用户信息
        document.getElementById('currentUserName').textContent = currentUser.realName || currentUser.username;

        // 加载统计数据
        loadStatistics();

        // 默认加载支付记录
        loadPayments();
    }

    // 切换标签页
    function switchTab(tabId) {
        // 切换标签状态
        document.querySelectorAll('.tab').forEach(tab => {
            tab.classList.remove('active');
        });
        document.querySelectorAll(`[onclick="switchTab('${tabId}')"]`).forEach(tab => {
            tab.classList.add('active');
        });

        // 切换内容显示
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.remove('active');
        });
        document.getElementById(tabId).classList.add('active');

        // 如果切换到支付记录标签，加载数据
        if (tabId === 'paymentRecords') {
            loadPayments();
        }
    }

    // 检查登录状态
    function checkLoginStatus() {
        const savedUser = localStorage.getItem('currentUser');
        if (savedUser) {
            currentUser = JSON.parse(savedUser);
        }
    }

    // 生成侧边栏菜单
    function generateSidebarMenu() {
        const sidebarMenu = document.getElementById('sidebarMenu');
        if (sidebarMenu && authManager) {
            sidebarMenu.innerHTML = authManager.generateSidebarMenu();
        }
    }

    // 切换侧边栏
    function toggleSidebar() {
        const sidebar = document.getElementById('sidebar');
        sidebar.classList.toggle('active');
    }

    // 退出登录
    function logout() {
        currentUser = null;
        localStorage.removeItem('currentUser');
        window.location.href = 'login.html';
        Utils.showMessage('已退出登录', 'info');
    }

    // 显示通知
    function showNotifications() {
        Utils.showMessage('通知功能开发中', 'info');
    }

    // 显示个人资料
    function showProfile() {
        Utils.showMessage('个人资料功能开发中', 'info');
    }

    // 修改密码
    function changePassword() {
        Utils.showMessage('修改密码功能开发中', 'info');
    }

    // 加载支付数据
    async function loadPayments(page = 1) {
        try {
            Utils.showLoading();

            const status = document.getElementById('paymentStatusFilter')?.value || '';
            const feeType = document.getElementById('paymentTypeFilter')?.value || '';
            const keyword = document.getElementById('paymentSearch')?.value || '';

            const response = await PaymentAPI.pagePayments(page, currentPageSize, keyword, feeType, status);

            if (response.result === 'SUCCESS') {
                renderPaymentTable(response.data.records);
                renderPagination('paymentPagination', page, response.data.pages, loadPayments);
                renderPaginationTools('paymentPaginationTools', response.data.pages,
                    (n) => { currentPageNum = n; loadPayments(n); },
                    (size) => { currentPageSize = size; currentPageNum = 1; loadPayments(1); }
                );
            } else {
                Utils.showMessage(response.message || '加载支付数据失败', 'error');
            }
        } catch (error) {
            Utils.showMessage('加载支付数据失败', 'error');
            console.error('Payments load error:', error);
        } finally {
            Utils.hideLoading();
        }
    }

    // 加载统计数据
    async function loadStatistics() {
        try {
            Utils.showLoading();
            const response = await PaymentAPI.getStatistics();

            if (response.result === 'SUCCESS') {
                const stats = response.data;
                document.getElementById('pendingAmount').textContent = Utils.formatMoney(stats.pendingAmount);
                document.getElementById('paidAmount').textContent = Utils.formatMoney(stats.paidAmount);
                document.getElementById('overdueCount').textContent = stats.overdueCount || 0;
                document.getElementById('damageCount').textContent = stats.damageCount || 0;
                document.getElementById('lostCount').textContent = stats.lostCount || 0;
            } else {
                Utils.showMessage(response.message || '加载统计数据失败', 'error');
            }
        } catch (error) {
            Utils.showMessage('加载统计数据失败', 'error');
            console.error('Statistics load error:', error);
        } finally {
            Utils.hideLoading();
        }
    }

    // 渲染支付表格
    function renderPaymentTable(payments) {
        const tbody = document.getElementById('paymentTableBody');
        if (!tbody) return;

        tbody.innerHTML = payments.map(payment => `
                <tr>
                    <td>${payment.paymentId}</td>
                    <td>${payment.username}</td>
                    <td>${getPaymentTypeText(payment.feeType)}</td>
                    <td>${Utils.formatMoney(payment.amount)}</td>
                    <td>${getPaymentMethodText(payment.paymentType)}</td>
                    <td><span class="status-badge status-${getPaymentStatusClass(payment.status)}">${getStatusText(payment.status)}</span></td>
                    <td>${Utils.formatDate(payment.createTime)}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="viewPaymentDetail(${payment.paymentId})">详情</button>
                        ${payment.status === 'unpaid' ? `
                            <button class="btn btn-sm btn-success" onclick="completePayment(${payment.paymentId})">完成支付</button>
                            <button class="btn btn-sm btn-warning" onclick="cancelPayment(${payment.paymentId})">取消</button>
                        ` : ''}
                    </td>
                </tr>
            `).join('');
    }

    // 获取费用类型文本
    function getPaymentTypeText(feeType) {
        if (!feeType) {
            return '未知类型';
        }

        const result = FEE_TYPE_ENUM[feeType];
        if (!result) {
            return `未知类型(${feeType})`;
        }

        return result;
    }

    // 获取支付方式文本
    function getPaymentMethodText(method) {
        const methodMap = {
            'alipay': '支付宝',
            'wechat': '微信支付',
            'cash': '现金',
            '': '-'
        };
        return methodMap[method] || (method || '-');
    }

    // 获取支付状态文本
    function getStatusText(status) {
        const statusMap = {
            'unpaid': '待支付',
            'paid': '已支付',
            'refunded': '已取消',
            'cancelled': '已取消'
        };
        return statusMap[status] || (status || '未知状态');
    }

    // 获取支付状态样式类
    function getPaymentStatusClass(status) {
        switch (status) {
            case 'unpaid': return 'unpaid';
            case 'paid': return 'paid';
            case 'refunded':
            case 'cancelled': return 'cancelled';
            default: return 'unpaid';
        }
    }

    // 搜索支付记录
    function searchPayments() {
        currentPageNum = 1;
        loadPayments(1);
    }

    // 查看支付详情
    async function viewPaymentDetail(paymentId) {
        try {
            Utils.showLoading();
            const response = await PaymentAPI.getPaymentById(paymentId);

            if (response.result === 'SUCCESS') {
                const payment = response.data;
                showModal('支付详情', `
                        <div class="payment-detail">
                            <div class="detail-row">
                                <label>支付ID:</label>
                                <span>${payment.paymentId}</span>
                            </div>
                            <div class="detail-row">
                                <label>用户:</label>
                                <span>${payment.username}</span>
                            </div>
                            <div class="detail-row">
                                <label>费用类型:</label>
                                <span>${getPaymentTypeText(payment.feeType)}</span>
                            </div>
                            <div class="detail-row">
                                <label>金额:</label>
                                <span>${Utils.formatMoney(payment.amount)}</span>
                            </div>
                            <div class="detail-row">
                                <label>支付方式:</label>
                                <span>${getPaymentMethodText(payment.paymentType)}</span>
                            </div>
                            <div class="detail-row">
                                <label>状态:</label>
                                <span class="status-badge status-${getPaymentStatusClass(payment.status)}">${getStatusText(payment.status)}</span>
                            </div>
                            <div class="detail-row">
                                <label>创建时间:</label>
                                <span>${Utils.formatDate(payment.createTime)}</span>
                            </div>
                            <div class="detail-row">
                                <label>支付时间:</label>
                                <span>${payment.paymentTime ? Utils.formatDate(payment.paymentTime) : '未支付'}</span>
                            </div>
                            <div class="detail-row">
                                <label>备注:</label>
                                <span>${payment.feeRecord?.remark || payment.remark || '-'}</span>
                            </div>
                        </div>
                    `, `
                        <button class="btn btn-secondary" onclick="closeModal()">关闭</button>
                    `);
            } else {
                Utils.showMessage(response.message || '获取支付详情失败', 'error');
            }
        } catch (error) {
            Utils.showMessage(error.message || '获取支付详情失败', 'error');
        } finally {
            Utils.hideLoading();
        }
    }

    // 完成支付 - 添加确认提示
    function completePayment(paymentId) {
        if (!confirm('确定要完成支付吗？')) return;

        showModal('完成支付', `
                <form id="completePaymentForm">
                    <input type="hidden" id="completePaymentId" value="${paymentId}">
                    <div class="form-group">
                        <label for="paymentMethod">支付方式</label>
                        <select id="paymentMethod" name="payMethod" required class="form-control">
                            <option value="">请选择支付方式</option>
                            <option value="alipay">支付宝</option>
                            <option value="wechat">微信支付</option>
                            <option value="cash">现金</option>
                        </select>
                    </div>
                </form>
            `, `
                <button class="btn btn-primary" onclick="submitCompletePayment()">确认支付</button>
                <button class="btn btn-secondary" onclick="closeModal()">取消</button>
            `);
    }

    // 提交完成支付
    async function submitCompletePayment() {
        const paymentId = parseInt(document.getElementById('completePaymentId').value);
        const payMethod = document.getElementById('paymentMethod').value;

        if (!payMethod) {
            Utils.showMessage('请选择支付方式', 'warning');
            return;
        }

        try {
            Utils.showLoading();
            const response = await PaymentAPI.completePayment(paymentId, payMethod);

            if (response.result === 'SUCCESS') {
                Utils.showMessage('支付完成', 'success');
                closeModal();
                loadPayments();
                loadStatistics();
            } else {
                Utils.showMessage(response.message || '支付失败', 'error');
            }
        } catch (error) {
            Utils.showMessage(error.message || '支付失败', 'error');
        } finally {
            Utils.hideLoading();
        }
    }

    // 取消支付 - 添加确认提示
    async function cancelPayment(paymentId) {
        if (!confirm('确定要取消该支付吗？')) return;

        try {
            Utils.showLoading();
            const response = await PaymentAPI.cancelPayment(paymentId);

            if (response.result === 'SUCCESS') {
                Utils.showMessage('支付已取消', 'success');
                loadPayments();
                loadStatistics();
            } else {
                Utils.showMessage(response.message || '取消失败', 'error');
            }
        } catch (error) {
            Utils.showMessage(error.message || '取消失败', 'error');
        } finally {
            Utils.hideLoading();
        }
    }

    /**
     * 计算并添加逾期罚款
     * 功能说明：查询用户的逾期借阅记录，计算费用，检查是否已有记录，无则添加
     */
    async function calculateOverdueFee() {
        const userId = document.getElementById('overdueUserId').value;
        const resultElement = document.getElementById('overdueFeeResult');

        if (!userId) {
            resultElement.textContent = '请输入用户ID';
            resultElement.className = 'fee-result error';
            return;
        }

        try {
            Utils.showLoading();
            const response = await PaymentAPI.calculateOverdueFee(userId);

            if (response.result === 'SUCCESS') {
                const fee = response.data;

                // 检查是否有逾期费用
                if (fee.amount <= 0) {
                    resultElement.textContent = `用户${userId}没有逾期记录或无需支付逾期费用`;
                    resultElement.className = 'fee-result info';
                } else {
                    // 检查是否已存在记录
                    if (fee.feeId) {
                        resultElement.textContent =
                            `用户${userId}的逾期罚款(${Utils.formatMoney(fee.amount)})已存在，无需重复添加`;
                        resultElement.className = 'fee-result info';
                    } else {
                        resultElement.textContent =
                            `操作成功: 用户${userId}的逾期罚款为 ${Utils.formatMoney(fee.amount)}，已添加到待支付费用`;
                        resultElement.className = 'fee-result success';
                        // 更新统计数据
                        loadStatistics();
                    }
                }
            } else {
                resultElement.textContent = response.message || '操作失败';
                resultElement.className = 'fee-result error';
            }
        } catch (error) {
            resultElement.textContent = error.message || '操作失败';
            resultElement.className = 'fee-result error';
        } finally {
            Utils.hideLoading();
        }
    }

    /**
     * 计算并添加损坏赔偿
     * 功能说明：根据用户ID、图书ID和赔偿比例计算费用，检查是否已有记录，无则添加
     */
    async function calculateDamageFee() {
        const userId = document.getElementById('damageUserId').value;
        const bookId = document.getElementById('damagedBookId').value;
        const damageRatio = parseFloat(document.getElementById('damageRatio').value);
        const resultElement = document.getElementById('damageFeeResult');

        // 验证输入
        if (!userId) {
            resultElement.textContent = '请输入用户ID';
            resultElement.className = 'fee-result error';
            return;
        }

        if (!bookId) {
            resultElement.textContent = '请输入图书ID';
            resultElement.className = 'fee-result error';
            return;
        }

        if (isNaN(damageRatio) || damageRatio <= 0 || damageRatio > 2) {
            resultElement.textContent = '请输入有效的赔偿比例（0.01-2之间）';
            resultElement.className = 'fee-result error';
            return;
        }

        try {
            Utils.showLoading();
            const response = await PaymentAPI.calculateDamageFee(userId, bookId, damageRatio);

            if (response.result === 'SUCCESS') {
                const fee = response.data;

                // 检查是否已存在记录
                if (fee.feeId) {
                    resultElement.textContent =
                        `用户${userId}的图书《${fee.bookName}》损坏赔偿(${Utils.formatMoney(fee.amount)})已存在，无需重复添加`;
                    resultElement.className = 'fee-result info';
                } else {
                    resultElement.textContent =
                        `操作成功: 用户${userId}的图书《${fee.bookName}》损坏赔偿费用为 ${Utils.formatMoney(fee.amount)}，已添加到待支付费用`;
                    resultElement.className = 'fee-result success';
                    // 更新统计数据
                    loadStatistics();
                }
            } else {
                resultElement.textContent = response.message || '操作失败';
                resultElement.className = 'fee-result error';
            }
        } catch (error) {
            resultElement.textContent = error.message || '操作失败';
            resultElement.className = 'fee-result error';
        } finally {
            Utils.hideLoading();
        }
    }

    /**
     * 计算并添加丢失赔偿
     * 功能说明：根据用户ID、图书ID和赔偿比例计算费用，检查是否已有记录，无则添加
     */
    async function calculateLostFee() {
        const userId = document.getElementById('lostUserId').value;
        const bookId = document.getElementById('lostBookId').value;
        const lostRatio = parseFloat(document.getElementById('lostRatio').value);
        const resultElement = document.getElementById('lostFeeResult');

        // 验证输入
        if (!userId) {
            resultElement.textContent = '请输入用户ID';
            resultElement.className = 'fee-result error';
            return;
        }

        if (!bookId) {
            resultElement.textContent = '请输入图书ID';
            resultElement.className = 'fee-result error';
            return;
        }

        if (isNaN(lostRatio) || lostRatio <= 0 || lostRatio > 3) {
            resultElement.textContent = '请输入有效的赔偿比例（0.01-3之间）';
            resultElement.className = 'fee-result error';
            return;
        }

        try {
            Utils.showLoading();
            const response = await PaymentAPI.calculateLostFee(userId, bookId, lostRatio);

            if (response.result === 'SUCCESS') {
                const fee = response.data;

                // 检查是否已存在记录
                if (fee.feeId) {
                    resultElement.textContent =
                        `用户${userId}的图书《${fee.bookName}》丢失赔偿(${Utils.formatMoney(fee.amount)})已存在，无需重复添加`;
                    resultElement.className = 'fee-result info';
                } else {
                    resultElement.textContent =
                        `操作成功: 用户${userId}的图书《${fee.bookName}》丢失赔偿费用为 ${Utils.formatMoney(fee.amount)}，已添加到待支付费用`;
                    resultElement.className = 'fee-result success';
                    // 更新统计数据
                    loadStatistics();
                }
            } else {
                resultElement.textContent = response.message || '操作失败';
                resultElement.className = 'fee-result error';
            }
        } catch (error) {
            resultElement.textContent = error.message || '操作失败';
            resultElement.className = 'fee-result error';
        } finally {
            Utils.hideLoading();
        }
    }

    // 显示模态框
    function showModal(title, body, footer) {
        document.getElementById('modalTitle').textContent = title;
        document.getElementById('modalBody').innerHTML = body;
        document.getElementById('modalFooter').innerHTML = footer;
        document.getElementById('modalOverlay').classList.add('active');
    }

    // 关闭模态框
    function closeModal() {
        document.getElementById('modalOverlay').classList.remove('active');
    }

    // 渲染分页组件
    function renderPagination(containerId, currentPage, totalPages, onPageChange) {
        const container = document.getElementById(containerId);
        if (!container) return;

        if (totalPages <= 1) {
            container.innerHTML = '';
            return;
        }

        container.innerHTML = '';
        container.appendChild(Utils.createPagination(currentPage, totalPages, onPageChange));
    }

    // 渲染分页工具栏：跳页与每页条数
    function renderPaginationTools(containerId, totalPages, onJump, onSizeChange) {
        const c = document.getElementById(containerId);
        if (!c) return;
        c.innerHTML = `
                <span>到第</span>
                <input id="${containerId}-jump" type="number" min="1" max="${totalPages}" value="${currentPageNum}" style="width:60px">
                <span>页</span>
                <button id="${containerId}-go" class="btn btn-sm btn-primary">确定</button>
                <span style="margin-left:12px">每页</span>
                <select id="${containerId}-size" style="width:90px">
                    <option ${currentPageSize==10?'selected':''} value="10">10 条/页</option>
                    <option ${currentPageSize==20?'selected':''} value="20">20 条/页</option>
                    <option ${currentPageSize==50?'selected':''} value="50">50 条/页</option>
                    <option ${currentPageSize==100?'selected':''} value="100">100 条/页</option>
                </select>
            `;
        const goBtn = document.getElementById(`${containerId}-go`);
        const jumpInput = document.getElementById(`${containerId}-jump`);
        const sizeSelect = document.getElementById(`${containerId}-size`);
        if (goBtn && jumpInput) {
            goBtn.onclick = () => {
                const n = parseInt(jumpInput.value || '1', 10);
                const page = Math.min(Math.max(1, n), totalPages);
                onJump(page);
            };
        }
        if (sizeSelect) {
            sizeSelect.onchange = () => {
                const size = parseInt(sizeSelect.value, 10);
                onSizeChange(size);
            };
        }
    }
</script>
</body>
</html>
